package com.regent.central.bill.web;

import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 日志拦截器
 *
 * @author 杨昌沛 646742615@qq.com
 * @date 2018-07-04 15:06
 **/
@Aspect
public class LoggingInterceptor {
    private final ObjectMapper mapper = new ObjectMapper();
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    public LoggingInterceptor() {
        mapper.setDefaultPrettyPrinter(new DefaultPrettyPrinter());
    }

    @Pointcut("execution(* com.regent.central.bill.web..*Controller.*(..))")
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        String signature = point.getSignature().toString();
        Object[] args = point.getArgs();
        if (logger.isInfoEnabled()) {
            String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(args.length == 1 ? args[0] : args);
            logger.info("request: [" + signature + "] with:\n<---------------- beginning ---------------->\n{}\n<---------------- finished ---------------->", json);
        }
        Object result = point.proceed();
        if (logger.isInfoEnabled()) {
            String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(result);
            logger.info("response: [" + signature + "] with:\n<---------------- beginning ---------------->\n{}\n<---------------- finished ---------------->", json);
        }
        return result;
    }

}
